package com.ruoyi.trainingManagement.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import jakarta.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.trainingManagement.domain.CourseStudentInfo;
import com.ruoyi.trainingManagement.domain.Vo.CourseAndTimeVo;
import com.ruoyi.trainingManagement.domain.Vo.CourseScheduleWithStudents;
import com.ruoyi.trainingManagement.service.ICourseStudentInfoService;
import com.ruoyi.trainingManagement.service.ItrainingProgramCoursesService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.trainingManagement.domain.CourseScheduleDetails;
import com.ruoyi.trainingManagement.service.ICourseScheduleDetailsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 课程排课详细信息Controller
 * 
 * @author chenxl
 * @date 2025-06-18
 */
@RestController
@RequestMapping("/trainingManagement/details")
public class CourseScheduleDetailsController extends BaseController
{
    @Autowired
    private ICourseScheduleDetailsService courseScheduleDetailsService;
    @Autowired
    private ICourseStudentInfoService courseStudentInfoService;
    @Autowired
    private ItrainingProgramCoursesService trainingProgramCoursesService;
    /**
     * 查询课程排课详细信息列表
     */
    //@PreAuthorize("@ss.hasPermi('trainingManagement:details:list')")
    @GetMapping("/list")
    public TableDataInfo list(CourseScheduleDetails courseScheduleDetails)
    {
        System.out.println("-------------------------------");
        //打印获取到的数据courseScheduleDetails
        System.out.println("获取到的数据courseScheduleDetails"+courseScheduleDetails);
        System.out.println("-------------------------------");
        // 检查所有培养方案课程是否都已开班通过
//        boolean allApproved = trainingProgramCoursesService.checkAllProgramsCourseApproved();
//        if (!allApproved) {
//            // 如果存在未审核通过的方案，返回空数据
//            return getDataTable(new ArrayList<>());
//        }
        startPage();
        List<CourseScheduleDetails> list = courseScheduleDetailsService.selectCourseScheduleDetailsList(courseScheduleDetails);
        return getDataTable(list);
    }

    /**
     * 导出课程排课详细信息列表
     */
    @PreAuthorize("@ss.hasPermi('trainingManagement:details:export')")
    @Log(title = "课程排课详细信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CourseScheduleDetails courseScheduleDetails)
    {
        List<CourseScheduleDetails> list = courseScheduleDetailsService.selectCourseScheduleDetailsList(courseScheduleDetails);
        ExcelUtil<CourseScheduleDetails> util = new ExcelUtil<CourseScheduleDetails>(CourseScheduleDetails.class);
        util.exportExcel(response, list, "课程排课详细信息数据");
    }

    /**
     * 获取课程排课详细信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('trainingManagement:details:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(courseScheduleDetailsService.selectCourseScheduleDetailsById(id));
    }

    /**
     * 新增课程排课详细信息
     */
    @PreAuthorize("@ss.hasPermi('trainingManagement:details:add')")
    @Log(title = "课程排课详细信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CourseScheduleDetails courseScheduleDetails)
    {
        courseScheduleDetails.setId(IdUtils.fastSimpleUUID());
        return toAjax(courseScheduleDetailsService.insertCourseScheduleDetails(courseScheduleDetails));
    }

    /**
     * 修改课程排课详细信息
     */
    @PreAuthorize("@ss.hasPermi('trainingManagement:details:edit')")
    @Log(title = "课程排课详细信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CourseScheduleDetails courseScheduleDetails)
    {
        System.out.println("-------------------------------");
        //打印获取到的数据
        System.out.println("获取到的数据"+courseScheduleDetails);
        System.out.println("-------------------------------");
        return toAjax(courseScheduleDetailsService.updateCourseScheduleDetails(courseScheduleDetails));
    }

    /**
     * 删除课程排课详细信息
     */
    @PreAuthorize("@ss.hasPermi('trainingManagement:details:remove')")
    @Log(title = "课程排课详细信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(courseScheduleDetailsService.deleteCourseScheduleDetailsByIds(ids));
    }
    /**
     * 使用遗传算法进行自动排课
     *
     * @param semesterId        学期ID
     * @param academicYear      学年
     * @param isScheduleCompleted 是否已完成排课状态（0-未排课，1-已排课）
     * @return 排课结果
     */
    @PostMapping("/auto-scheduling")
    public AjaxResult autoCourseScheduling(
            @RequestParam("semesterId") int semesterId,
            @RequestParam("academicYear") int academicYear,
            @RequestParam(value = "isScheduleCompleted", defaultValue = "0") int isScheduleCompleted) {

        //打印获取到的数据
        System.out.println("学期ID："+semesterId+"学年："+academicYear+"是否已完成排课状态："+isScheduleCompleted);
        return courseScheduleDetailsService.autoCourseScheduling(semesterId, academicYear, isScheduleCompleted);
    }

    /**
     * 分配教师到班级
     * @param classId 班级ID
     * @param teacherId 教师ID
     * @return 操作结果
     */
    @PreAuthorize("@ss.hasPermi('trainingManagement:details:edit')")
    @Log(title = "分配教师", businessType = BusinessType.UPDATE)
    @PutMapping("/assignTeacher")
    public AjaxResult assignTeacher(@RequestBody Map<String, String> params) {
        System.out.println("-------------------------------");
        String classId = params.get("classId");
        String teacherId = params.get("teacherId");
        //String classroom = params.get("classroom");
        System.out.println("班级ID："+classId+"教师ID："+teacherId);
        System.out.println("-------------------------------");
        if (classId == null || teacherId == null) {
            return AjaxResult.error("班级ID和教师ID不能为空");
        }

        int result = courseScheduleDetailsService.updateTeacherIdById(classId, teacherId);
        return result > 0 ?
                AjaxResult.success("教师分配成功") :
                AjaxResult.error("未找到对应班级");
    }
    //通过课程ID、学期ID和年级查询课程排课信息以及学生名单
    @GetMapping("/getCourseScheduleDetailsAndStudentList")
    public AjaxResult getCourseScheduleDetailsAndStudentList(
            @RequestParam("courseId") String courseId,
            @RequestParam("semesterId") int semesterId,
            @RequestParam("grade") int grade) {
        //打印传入的 数据
        System.out.println("传入的 数据：" + "课程ID：" + courseId + "学期ID：" + semesterId + "年级：" + grade);
        // 1. 查询所有符合条件的课程班信息
        List<CourseScheduleDetails> courseScheduleDetailsList =
                courseScheduleDetailsService.selectByCourseSemesterGrade(courseId, semesterId, grade);

        // 2. 构建返回结果：每个课程班包含其学生名单
        List<CourseScheduleWithStudents> result = new ArrayList<>();
        for (CourseScheduleDetails courseSchedule : courseScheduleDetailsList) {
            // 3. 查询该课程班的学生名单
            List<CourseStudentInfo> studentList =
                    courseStudentInfoService.selectByCourseScheduleDetailsId(courseSchedule.getId());

            // 4. 封装课程班信息和学生名单到统一对象中
            CourseScheduleWithStudents scheduleWithStudents = new CourseScheduleWithStudents();
            scheduleWithStudents.setCourseScheduleDetails(courseSchedule);
            scheduleWithStudents.setStudentList(studentList);

            result.add(scheduleWithStudents);
        }

        // 5. 返回结构化数据
        return AjaxResult.success(result);
    }
    /**
     * 通过教师ID获取对应的全部课程班及时间安排信息
     * @param teacherId 教师ID
     * @return 课程班信息及时间安排列表
     */
    @PreAuthorize("@ss.hasPermi('trainingManagement:details:query')")
    @GetMapping("/getCourseScheduleDetailsByTeacherId")
    public AjaxResult getCourseScheduleDetailsByTeacherId(@RequestParam String teacherId) {
        // 参数非空校验
        if (teacherId == null || teacherId.trim().isEmpty()) {
            return AjaxResult.error("教师ID不能为空");
        }

        // 调用服务层查询数据
        List<CourseAndTimeVo> courseAndTimeVoList = courseScheduleDetailsService.getCourseAndTimeVoListByTeacherId(teacherId);

        // 返回结果（空数据时返回空列表，避免前端处理null）
        return AjaxResult.success(courseAndTimeVoList == null ? new ArrayList<>() : courseAndTimeVoList);
    }

}
